import axios from 'axios'

// LeanCloud配置
const LEANCLOUD_CONFIG = {
    appId: 'U4na1Qpwp3tGD2sG1lFlqXev-gzGzoHsz',
    appKey: 'rWhaBLGNJ18O1XgOXtHxon3i',
    masterKey: 'LEo0q93YTnTcqXvUh7789nra',
    serverURL: 'https://u4na1qpw.lc-cn-n1-shared.com',
}

// 创建axios实例
const instance = axios.create({
    baseURL: `${LEANCLOUD_CONFIG.serverURL}/1.1`,
    timeout: 10000,
    headers: {
        'X-LC-Id': LEANCLOUD_CONFIG.appId,
        'X-LC-Key': LEANCLOUD_CONFIG.appKey,
        'Content-Type': 'application/json',
    },
})

// 请求拦截器
instance.interceptors.request.use(
    (config) => {
        // 添加时间戳防止缓存
        if (config.method === 'get') {
            config.params = {
                ...config.params,
                _t: Date.now(),
            }
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    },
)

// 响应拦截器 - 包含重试机制
instance.interceptors.response.use(
    (response) => {
        return response.data
    },
    async (error) => {
        const originalRequest = error.config

        // 如果请求已经重试过，直接拒绝
        if (originalRequest._retryCount >= 3) {
            return Promise.reject(error)
        }

        // 设置重试次数
        originalRequest._retryCount = originalRequest._retryCount || 0

        // 如果是网络错误或超时，进行重试
        if (!error.response || error.code === 'ECONNABORTED') {
            originalRequest._retryCount += 1

            // 延迟重试，延迟时间随重试次数增加
            const delay = Math.pow(2, originalRequest._retryCount) * 1000

            await new Promise((resolve) => setTimeout(resolve, delay))

            return instance(originalRequest)
        }

        // 处理HTTP错误
        if (error.response) {
            const { status, data } = error.response

            switch (status) {
                case 401:
                    console.error('认证失败，请重新登录')
                    break
                case 403:
                    console.error('权限不足')
                    break
                case 404:
                    console.error('请求的资源不存在')
                    break
                case 500:
                    console.error('服务器内部错误')
                    break
                default:
                    console.error(`请求错误: ${status}`)
            }

            // 返回统一的错误格式
            return Promise.reject({
                code: status,
                message: data.error || '请求失败',
                data: data,
            })
        }

        return Promise.reject(error)
    },
)

// 导出封装的请求方法
export const request = {
    get(url, params = {}) {
        return instance.get(url, { params })
    },

    post(url, data = {}) {
        return instance.post(url, data)
    },

    put(url, data = {}) {
        return instance.put(url, data)
    },

    delete(url) {
        return instance.delete(url)
    },
}

export default instance
